package com.joshondesign.sdljava.demo;

import com.joshondesign.sdljava.SDL;
import com.joshondesign.sdljava.SDLUtil;
import com.joshondesign.sdljava.SDL_Surface;
import com.joshondesign.sdljava.gfx.*;

import java.io.File;
import java.nio.Buffer;
import java.nio.ByteBuffer;

public class BlurTest implements SDLUtil.InitCallback {

    public static void main(String ... args) {
        SDLUtil.init(new BlurTest());
    }

    public void callback() throws Exception {
        Util.standard_init();
        SDL_Surface surface = Util.createResizableWindow(800, 600);
        final Scene scene = new Scene(surface);
        scene.setBackgroundFill(SColor.BLACK);
        Layer layer = new Layer(surface.getFormat());
        scene.add(layer);

        final SImage image = new SImage(new File("src/resources/andromeda.jpg"));
        layer.add(new Node() {
            @Override
            public void draw(GFX gfx) {
                SBuffer buffer = gfx.createBuffer(200,100);

                int r = 10; // blur radius, 0 means just the center pixel.
                for(int x=1; x<99; x++) {
                    for(int y=1; y<99; y++) {
                        int totalA = 0;
                        int totalR = 0;
                        int totalG = 0;
                        int totalB = 0;
                        for(int k=0-r; k<1+r; k++) {
                            for(int j= 0-r; j<1+r; j++) {
                                int px = x+k;
                                int py = y+j;
                                long color = SDL.getPixel((SDL_Surface)image.getNative(),px,py);
                                totalA += (color & 0x000000FF) >> 0;
                                totalR += (color & 0x0000FF00) >> 8;
                                totalG += (color & 0x00FF0000) >> 16;
                                totalB += (color & 0xFF000000) >> 24;
                            }
                        }
                        int div = (r*2+1)*(r*2+1);
                        long total =
                                 ((totalA/div)<<24)
                                | ((totalR/div)<<16)
                                | ((totalG/div)<<8)
                                |  ((totalB/div)<<0)
                                ;
                        SDL.setPixel(buffer.getNative(),x,y,total);
                    }
                }

                gfx.drawBuffer(buffer,0,0);
                gfx.drawImage(image,200,0);
            }
        });
        scene.start();
    }
}
